package com.ruide.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.ruide.mapper.IMapper;

public class DBManager {
	private Connection getConn(){
		try {
			Connection conn=DBHelper.cpds.getConnection();
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	public int executeUpdate(String sql,Object params[]){
		Connection conn=null;
		PreparedStatement pst=null;
		try{
			conn=getConn();
			pst=conn.prepareStatement(sql);
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pst.setObject(i+1,params[i]);
				}
			}
			int i=pst.executeUpdate();
			return i;
		}catch(SQLException ex){
			ex.printStackTrace();
		}finally{
			try {
				pst.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return -1;
	}
	public int executeQueryCount(String sql,Object params[]){
		Connection conn=null;
		PreparedStatement pst=null;
		ResultSet rst=null;
		try{
			conn=getConn();
			pst=conn.prepareStatement(sql);
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pst.setObject(i+1,params[i]);
				}
			}
			rst=pst.executeQuery();
			rst.next();
			int i=rst.getInt(1);
			return i;
		}catch(SQLException ex){
			ex.printStackTrace();
		}finally{
			try {
				rst.close();
				pst.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return -1;		
	}
	public List executeQuery(String sql,IMapper mapper,Object params[]){
		Connection conn=null;
		PreparedStatement pst=null;
		ResultSet rst=null;
		try{
			conn=getConn();
			pst=conn.prepareStatement(sql);
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pst.setObject(i+1,params[i]);
				}
			}
			rst=pst.executeQuery();
			List list=mapper.map(rst);
			return list;
		}catch(SQLException ex){
			ex.printStackTrace();
		}finally{
			try {
				rst.close();
				pst.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
